package com.shangyueshang.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shangyueshang.common.SysConstants;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/6 19:39
 * @version: v1.0.0
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //登录接口跳过token检查
        if (!SysConstants.login.equalsIgnoreCase(request.getRequestURI())) {
            //获取token并检查登录状态
            //token过期需要重登陆
            try {
                SecurityUtil.checkAuthentication(request);
            } catch (CredentialsExpiredException e) {
                response.setContentType(MediaType.APPLICATION_JSON.toString());
                PrintWriter writer = response.getWriter();
                HttpResult result = HttpResult.fail(401, "登录已过期,请重新登录!");
                writer.write(new ObjectMapper().writeValueAsString(result));
                writer.flush();
                writer.close();
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
